package com.bracketbird.server;

import com.bracketbird.client.service.*;
import com.bracketbird.server.services.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

/**
 * Implementing once a day cron job. url /gwtmodule/onceaday
 */
public class OnceADayServiceImpl extends HttpServlet {
    private static final long serialVersionUID = 274804192869160632L;


    public void init() {
        ActionHandlerRegistry.init(getServletContext());
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        handleRequest(request);
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        handleRequest(request);
    }


    private void handleRequest(HttpServletRequest request) {
        //only requests from google cron job maschine should be handled
        String cronJob = request.getHeader("X-AppEngine-Cron");

        if (cronJob == null || !cronJob.equalsIgnoreCase("true")) {
            return;
        }
        try {

            //supports only two retries
            String retried = request.getHeader("X-AppEngine-TaskRetryCount");
            if (retried != null && retried.equals("2")) {
                Logger.log("OnceADay exceeded maximum number of re-tries.");
                return;
            }


            ActionHandlerRegistry.executeAction(new OnceADayCronJobAction());
        }
        catch (Exception e) {
            //Ignore - handled in ActionHandlerRegistry
            
        }

    }

}





